package com.example.xyxwebbackend001.service;


import com.example.xyxwebbackend001.config.FileUploadConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FilenameUtils;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.UUID;
@Service
public class FileStorageService {

    private final FileUploadConfig config;

    @Autowired
    public FileStorageService(FileUploadConfig config) {
        this.config = config;
    }

    public List<String> storeFiles(MultipartFile[] files, String moduleType) throws IOException {
        List<String> filePaths = new ArrayList<>();

        // 根据模块类型获取对应存储路径
        String storageBaseDir = switch (moduleType) {
            case "home" -> config.getDefaultHomeDir();
            case "com" -> config.getUploadComDir();
            case "cult" -> config.getUploadCultDir();
            case "avatar" -> config.getUploadAvatarDir();
            default -> config.getUploadDir(); // 默认存储路径
        };

        for (MultipartFile file : files) {
            String fileType = FilenameUtils.getExtension(file.getOriginalFilename());
            String fileName = UUID.randomUUID() + "." + fileType;

            // 构建完整存储路径
            Path storagePath = Paths.get(storageBaseDir, fileName);
            Files.createDirectories(storagePath.getParent());
            Files.copy(file.getInputStream(), storagePath);

            // 返回相对访问路径
            filePaths.add(fileName);
        }
        return filePaths;
    }
    public boolean deleteFile(String fileName, String moduleType) throws IOException {
        // 获取对应模块的存储路径
        String storageBaseDir = switch (moduleType) {
            case "home" -> config.getDefaultHomeDir();
            case "com" -> config.getUploadComDir();
            case "cult" -> config.getUploadCultDir();
            case "avatar" -> config.getUploadAvatarDir();
            default -> config.getUploadDir();
        };

        Path filePath = Paths.get(storageBaseDir, fileName);
        return Files.deleteIfExists(filePath);
    }

    public void deleteFiles(List<String> fileNames, String moduleType) throws IOException {
        for (String fileName : fileNames) {
            deleteFile(fileName, moduleType);
        }
    }
}